package com.kvn.interceptor;

import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;

/**
 * Created by wangzhiyuan on 2018/6/6
 */
public class TableNameModifier extends MySqlASTVisitorAdapter {
    private String tableName;
    private String newTableName;

    public TableNameModifier(String tableName, String newTableName) {
        this.tableName = tableName;
        this.newTableName = newTableName;
    }

    @Override
    public boolean visit(SQLSelectStatement astNode) {
        astNode.getSelect().accept(this);
        return false;
    }

    @Override
    public boolean visit(SQLSelect x) {
        x.getQuery().accept(this);
        return false;
    }

    @Override
    public boolean visit(SQLExprTableSource x) {
        x.getExpr().accept(this);
        return false;
    }

    @Override
    public boolean visit(SQLIdentifierExpr x) {
        if (x.getName().toLowerCase().trim().equals(tableName)) {
            x.setName(newTableName);
        }
        return false;
    }
}
